package cn.tedu._07vehicle.controller;

import cn.tedu._07vehicle.base.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author tune_the last
 * @date 2025/11/19 - 11:11
 */
@Slf4j
@RestController
@RequestMapping("/v1/file")
public class UploadController {
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        //终极目标：将文件保存到服务器的指定目录中：
        //1.获取原始文件名
        String filename = file.getOriginalFilename();
        //2.获取文件名中的后缀:
        String suffix = filename.substring(filename.lastIndexOf("."));
        //3.删除全球唯一的文件名：
        filename = UUID.randomUUID() +suffix;

        String dirPath = "D:/ideaWorkSpace2/files/";
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        File f = new File(dirPath + datePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        String filePath = dirPath + datePath + filename;
        log.debug("filePath: " + filePath);
        file.transferTo(new File(filePath));
        return Result.ok();
    }
}
